<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="文件版本编号" prop="versionId">
        <el-input v-model="formData.versionId" placeholder="请输入文件版本编号" />
      </el-form-item>
      <el-form-item label="父步骤编号" prop="parentId">
        <el-tree-select
          v-model="formData.parentId"
          :data="processDiagramTree"
          :props="{...defaultProps, label: 'description'}"
          check-strictly
          default-expand-all
          placeholder="请选择父步骤编号"
        />
      </el-form-item>
      <el-form-item label="步骤序号" prop="step">
        <el-input v-model="formData.step" placeholder="请输入步骤序号" />
      </el-form-item>
      <el-form-item label="简述" prop="description">
        <Editor v-model="formData.description" height="150px" />
      </el-form-item>
      <el-form-item label="输入物料列表" prop="materialInputList">
        <el-input v-model="formData.materialInputList" placeholder="请输入输入物料列表" />
      </el-form-item>
      <el-form-item label="输入物料列表" prop="informationInputList">
        <el-input v-model="formData.informationInputList" placeholder="请输入输入物料列表" />
      </el-form-item>
      <el-form-item label="输出图片" prop="processOutputPicture">
        <UploadImg v-model="formData.processOutputPicture" />
      </el-form-item>
      <el-form-item label="操作类别" prop="operateCate">
        <el-radio-group v-model="formData.operateCate">
          <el-radio 
v-for="dict in getStrDictOptions(DICT_TYPE.MANU_PROCESS_CATEGORY)" :key="dict.value"
            :label="dict.label"
            :value="dict.value">{{dict.label}}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="是否有追属性" prop="withTrace">
        <el-radio-group v-model="formData.withTrace">
          <el-radio
            v-for="dict in getBoolDictOptions(DICT_TYPE.INFRA_BOOLEAN_STRING)"
            :key="dict.value"
            :label="dict.value"
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="防错等级" prop="mpLevel">
        <el-input v-model="formData.mpLevel" placeholder="请输入防错等级" />
      </el-form-item>
      <el-form-item label="是关键特性" prop="kcOrCc">
        <el-input v-model="formData.kcOrCc" placeholder="请输入是关键特性" />
      </el-form-item>
      <el-form-item label="操作时间" prop="cycleTime">
        <el-input v-model="formData.cycleTime" placeholder="输入操作时间" />
      </el-form-item>
      <el-form-item label="工作站id" prop="stationId">
        <el-input v-model="formData.stationId" placeholder="请输入工作站id" />
      </el-form-item>
      <el-form-item label="输出要求" prop="requirement">
        <el-input v-model="formData.requirement" placeholder="请输入输出要求" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { getBoolDictOptions, DICT_TYPE,getStrDictOptions } from '@/utils/dict'
import { ProcessDiagramApi, ProcessDiagramVO } from '@/api/manu/processdiagram'
import { defaultProps, handleTree } from '@/utils/tree'

/** 工艺路径 表单 */
defineOptions({ name: 'ProcessDiagramForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  versionId: undefined,
  parentId: undefined,
  step: undefined,
  description: undefined,
  materialInputList: undefined,
  informationInputList: undefined,
  processOutputPicture: undefined,
  operateCate: undefined,
  withTrace: undefined,
  mpLevel: undefined,
  kcOrCc: undefined,
  cycleTime: undefined,
  stationId: undefined,
  requirement: undefined,
})
const formRules = reactive({
  versionId: [{ required: true, message: '文件版本编号不能为空', trigger: 'blur' }],
  step: [{ required: true, message: '步骤序号不能为空', trigger: 'blur' }],
  mpLevel: [{ required: true, message: '防错等级不能为空', trigger: 'blur' }],
  cycleTime: [{ required: true, message: '操作时间不能为空', trigger: 'blur' }],
  stationId: [{ required: true, message: '工作站id不能为空', trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref
const processDiagramTree = ref() // 树形结构

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await ProcessDiagramApi.getProcessDiagram(id)
    } finally {
      formLoading.value = false
    }
  }
  await getProcessDiagramTree()
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as ProcessDiagramVO
    if (formType.value === 'create') {
      await ProcessDiagramApi.createProcessDiagram(data)
      message.success(t('common.createSuccess'))
    } else {
      await ProcessDiagramApi.updateProcessDiagram(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    versionId: undefined,
    parentId: undefined,
    step: undefined,
    description: undefined,
    materialInputList: undefined,
    informationInputList: undefined,
    processOutputPicture: undefined,
    operateCate: undefined,
    withTrace: undefined,
    mpLevel: undefined,
    kcOrCc: undefined,
    cycleTime: undefined,
    stationId: undefined,
    requirement: undefined,
  }
  formRef.value?.resetFields()
}

/** 获得工艺路径树 */
const getProcessDiagramTree = async () => {
  processDiagramTree.value = []
  const data = await ProcessDiagramApi.getProcessDiagramList()
  const root: Tree = { id: 0, name: '顶级工艺路径', children: [] }
  root.children = handleTree(data, 'id', 'parentId')
  processDiagramTree.value.push(root)
}
</script>